package com.clps.digital.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.digest.MD5;
import com.clps.digital.dao.UserDao;
import com.clps.digital.model.dto.user.UserLoginRequest;
import com.clps.digital.model.entity.User;
import com.clps.digital.model.vo.UserLoginVo;
import com.clps.digital.service.UserService;
import com.clps.digital.util.TokenCache;
import com.clps.digital.util.UserContext;

import java.math.BigDecimal;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author: Chase
 * @date: 2024/8/29 21:31
 * @Version: 1.0
 * @description:
 */

public class UserServiceImpl implements UserService {

    private UserDao userDao;

    /**
     * 获取当前登录的用户信息
     * @param userId
     * @return
     */
    @Override
    public User getUser(Long userId) {
        if (ObjectUtil.isEmpty(userId)) {
            return new User();
        }
        User user = userDao.getUser(userId);
        return user;
    }

    /**
     * 注册用户
     * @param user
     * @return
     */
    @Override
    public Long insertUser(User user) {
        if (ObjectUtil.isEmpty(user)) {
            return null;
        }
        user.setUserPassword(MD5.create().digestHex(user.getUserPassword()));
        return userDao.insertUser(user);
    }

    /**
     * 登录
     * @param userLoginRequest
     * @return
     */
    @Override
    public UserLoginVo login(UserLoginRequest userLoginRequest) {
        User user = userDao.login(userLoginRequest.getUserAccount(), MD5.create().digestHex(userLoginRequest.getUserPassword()));
        if (ObjectUtil.isEmpty(user)) {
            return null;
        }
        UserLoginVo userLoginVo = new UserLoginVo();
        BeanUtil.copyProperties(user, userLoginVo);
        String token = UUID.randomUUID().toString().replace("-", "");
        TokenCache.put(token, user.getId(), 30L, TimeUnit.MINUTES);
        userLoginVo.setToken(token);
        return userLoginVo;
    }

    /**
     * 更新用户信息
     * @param user
     * @return
     */
    @Override
    public Boolean updateUser(User user) {
        user.setId(UserContext.getUser());
        return userDao.updateUser(user);
    }


    /*
    * @Author 小炎子
    * @Description 增加余额
    * @Date 上午10:42 2024/9/5
    */
    @Override
    public void addBalance(Integer money) {
        Long userId = UserContext.getUser();
        User user = userDao.getUser(userId);
        user.setUserBalance(user.getUserBalance().add(BigDecimal.valueOf(money)));
        userDao.saveUser(user);
    }
}
